package com.rytx.web.controller.ysp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;

import com.rytx.common.core.domain.R;
import com.rytx.common.core.domain.entity.SysUser;
import com.rytx.common.core.domain.model.LoginUser;
import com.rytx.system.service.IArtOrderAfterService;
import com.rytx.system.service.IArtRentalService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.rytx.common.annotation.Log;
import com.rytx.common.core.controller.BaseController;
import com.rytx.common.core.domain.AjaxResult;
import com.rytx.common.enums.BusinessType;
import com.rytx.system.domain.ysp.ArtOrder;
import com.rytx.system.service.IArtOrderService;
import com.rytx.common.utils.poi.ExcelUtil;
import com.rytx.common.core.page.TableDataInfo;

/**
 * 艺术订单信息Controller
 *
 * @author rytx
 * @date 2024-05-12
 */
@RestController
@RequestMapping("/system/order")
@Api(value = "ArtOrderController", tags = "订单接口")
public class ArtOrderController extends BaseController
{
    @Autowired
    private IArtOrderService artOrderService;

    @Autowired
    private IArtRentalService artRentalService;

    @Autowired
    private IArtOrderAfterService artOrderAfterService;

    @PostMapping("/manualProcessing")
    @ApiOperation(value = "手动处理免押异常订单", notes = "手动处理免押异常订单")
    public AjaxResult manualProcessing(@RequestBody ArtOrder order){
        return artOrderService.manualProcessing(order);
    }

    @PostMapping("/cancelLeaseRenewal")
    @ApiOperation(value = "手动取消续租", notes = "手动取消续租，传订单编号orderNo")
    public AjaxResult cancelLeaseRenewal(ArtOrder order){
        return artOrderService.cancelLeaseRenewal(order);
    }

    @PostMapping("/confirmReceipt")
    @ApiOperation(value = "手动确认收货", notes = "手动确认收货，传订单编号orderNo")
    public AjaxResult confirmReceipt(ArtOrder order){
        return artOrderService.confirmReceipt(order);
    }

    @PostMapping("/manualMaiduan")
    @ApiOperation(value = "手动买断", notes = "手动买断，传订单编号orderNo")
    public AjaxResult manualMaiduan(ArtOrder order){
        return artOrderService.manualMaiduan(order);
    }

    @PostMapping("/manualLeaseRenewal")
    @ApiOperation(value = "手动续租", notes = "续租，传订单编号orderNo和租期rentalDays")
    public AjaxResult manualLeaseRenewal(ArtOrder order){
        return artOrderService.manualLeaseRenewal(order);
    }

    @PostMapping("/callbackZmOrder")
    @ApiOperation(value = "免单成功后回调艺术订单接口", notes = "免单成功后回调艺术订单接口，把支付宝返回的消息传递回来")
    public AjaxResult callbackZmOrder(String message){
        LoginUser loginUser = getLoginUser();
        if(loginUser.getArtUser() == null){
            return AjaxResult.error("用户未登录");
        }
        Long userid = loginUser.getArtUser().getId();
        if(userid == null){
            return AjaxResult.error("用户未找到");
        }
        return artOrderService.callbackZmOrder(message);
    }

    @PostMapping("/completeZmOrder")
    @ApiOperation(value = "完成免押订单", notes = "完成免押订单，传订单编号orderNo")
    public AjaxResult completeZmOrder(ArtOrder order){
//        LoginUser loginUser = getLoginUser();
//        if(loginUser.getArtUser() == null){
//            return AjaxResult.error("用户未登录");
//        }
//        Long userid = loginUser.getArtUser().getId();
//        if(userid == null){
//            return AjaxResult.error("用户未找到");
//        }
//        order.setUserId(userid);
        return artOrderService.manualCompleteZmOrder(order);
    }

    @PostMapping("/refundZmOrder")
    @ApiOperation(value = "租赁订单退款申请", notes = "租赁订单退款申请，传订单编号orderNo")
    public AjaxResult refundZmOrder(ArtOrder order){
        return artOrderService.refundZmOrder(order);
    }

    @PostMapping("/refundZFBOrderOperate")
    @ApiOperation(value = "后台处理支付宝订单仅退款申请", notes = "后台处理支付宝订单仅退款申请")
    public AjaxResult refundZFBOrderOperate(ArtOrder order){
        return artOrderService.refundZFBOrderOperate(order);
    }

    /**
     * 查询艺术订单信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/list")
    public TableDataInfo list(ArtOrder artOrder)
    {
        startPage();
        List<ArtOrder> list = artOrderService.selectArtOrderList(artOrder);
        return getDataTable(list);
    }

    /**
     * 待发货订单
     */
    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/deliveryList")
    public TableDataInfo deliveryList(ArtOrder artOrder)
    {
        startPage();
        List<ArtOrder> list = artOrderService.deliveryList(artOrder);
        return getDataTable(list);
    }

    /**
     * 追缴订单
     */
    @PreAuthorize("@ss.hasPermi('system:order:list')")
    @GetMapping("/recoveryList")
    public TableDataInfo recoveryList(ArtOrder artOrder)
    {
        startPage();
        List<ArtOrder> list = artOrderService.recoveryList(artOrder);
        return getDataTable(list);
    }

    @GetMapping("/appRecoveryList")
    public TableDataInfo appRecoveryList(ArtOrder artOrder)
    {
        LoginUser loginUser = getLoginUser();
        Long userid = loginUser.getArtUser().getId();
        artOrder.setUserId(userid);

        if(artOrder.getRecoveryStatus() == null){
            artOrder.setRecoveryStatus("0"); // 无追缴状态
        }

        startPage();
        List<ArtOrder> list = artOrderService.appRecoveryList(artOrder);
        List<Map<String,Object>> listMap = new ArrayList<>();
        for(ArtOrder order:list){
            Map<String,Object> map = new HashMap<>();
            map.put("order",order);
            map.put("rental",artRentalService.selectArtRentalById(order.getArtRentalId()));
            listMap.add(map);
        }
        return getDataTable(listMap);
    }

    @GetMapping("/appList")
    public TableDataInfo listByUserId(ArtOrder artOrder)
    {
        LoginUser loginUser = getLoginUser();
        Long userid = loginUser.getArtUser().getId();
        artOrder.setUserId(userid);

        if(artOrder.getRecoveryStatus() == null){
//            artOrder.setRecoveryStatus("0"); // 无追缴状态
        }

        startPage();
        List<ArtOrder> list = artOrderService.appSelectArtOrderList(artOrder);
        List<Map<String,Object>> listMap = new ArrayList<>();
        for(ArtOrder order:list){
            Map<String,Object> map = new HashMap<>();
            // 组装租赁的主订单，是否有子订单，总租期，总租金，租赁结束时间
            artOrderService.assemblyLeaseMainOrder(order);
            map.put("order",order);
            map.put("orderAfter",artOrderAfterService.getOrderAfterInfo(order.getOrderNo()));
            map.put("rental",order.getCartRentalIds() == null ? new ArrayList<>() : artRentalService.selectArtRentalByIds(order.getCartRentalIds()));
            listMap.add(map);
        }
        return getDataTable(listMap);
    }

    /**
     * 查询是否存在逾期订单
     *
     * @param artOrder 艺术订单信息
     * @return 预期信息
     */
    @GetMapping("/overdueList")
    public TableDataInfo overdueList(ArtOrder artOrder)
    {
        LoginUser loginUser = getLoginUser();
        Long userid = loginUser.getArtUser().getId();
        System.out.println(userid);
        artOrder.setUserId(userid);
        startPage();
        List<ArtOrder> list = artOrderService.selectArtOrderOverdue(artOrder);
        return getDataTable(list);
    }
    /**
     * 导出艺术订单信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:order:export')")
    @Log(title = "艺术订单信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ArtOrder artOrder)
    {
        List<ArtOrder> list = artOrderService.selectArtOrderList(artOrder);
        ExcelUtil<ArtOrder> util = new ExcelUtil<ArtOrder>(ArtOrder.class);
        util.exportExcel(response, list, "艺术订单信息数据");
    }

    /**
     * 获取艺术订单信息详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:order:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(artOrderService.selectArtOrderById(id));
    }

    /**
     * 新增艺术订单信息
     */
    @PreAuthorize("@ss.hasPermi('system:order:add')")
    @Log(title = "艺术订单信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ArtOrder artOrder)
    {
        return toAjax(artOrderService.insertArtOrder(artOrder));
    }

    /**
     * 修改艺术订单信息
     */
    @PreAuthorize("@ss.hasPermi('system:order:edit')")
    @Log(title = "艺术订单信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ArtOrder artOrder)
    {
        return toAjax(artOrderService.updateArtOrder(artOrder));
    }

    /**
     * 删除艺术订单信息
     */
    @PreAuthorize("@ss.hasPermi('system:order:remove')")
    @Log(title = "艺术订单信息", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(artOrderService.deleteArtOrderByIds(ids));
    }

    /**
     * 查看订单详情
     * @param id 订单id
     * @return
     */
    @GetMapping("/orderdetails")
    public AjaxResult orderdetails(Long id,Long artRentalId)
    {
        Map<String,Object> map =new HashMap<>();
        map.put("order",artOrderService.orderdetails(id));
        map.put("rental",artRentalService.selectArtRentalById(artRentalId));
        return success(map);
    }
    /**
     * 租赁订单往期列表查询（第二级）
     *
     * @param artOrder 艺术订单信息
     * @return 预期信息
     */
    @GetMapping("/orderTwoList")
    public TableDataInfo orderTwoList(ArtOrder artOrder)
    {
        LoginUser loginUser = getLoginUser();
        Long userid = loginUser.getArtUser().getId();
        System.out.println(userid);
//        artOrder.setUserId(userid);
        artOrder.setOrderType("1");
        artOrder.setParentOrderNo(artOrder.getOrderNo());
        artOrder.setOrderNo(null);
        startPage();
        List<ArtOrder> list = artOrderService.orderTwoList(artOrder);
        List<Map<String,Object>> listMap = new ArrayList<>();
        for(ArtOrder order:list){
            Map<String,Object> map = new HashMap<>();
            map.put("order",order);
            map.put("rental",artRentalService.selectArtRentalById(order.getArtRentalId()));
            listMap.add(map);
        }
        return getDataTable(listMap);
    }
}
